package com.app.common.net.jl

import com.app.common.net.BaseProtocol
import com.app.common.net.HttpProtocol
import com.app.common.net.Response

class ApiJLService(ip: String = API_HOST_IP_JL) : BaseProtocol {

    override fun release() {
        httpProtocol.release()
    }

    companion object{
        const val API_HOST_IP_JL = "192.168.1.8" //default
    }

    private val httpProtocol = HttpProtocol(true)
    private val apiResponseConverter = JlApiResponseConverter()
    private val host = "http://$ip/"


    private suspend fun <T> asyncApiRequest(
        name: String,
        vararg query: String,
        converter: HttpProtocol.Converter<T>
    ): T {
        val value = if (query.isEmpty()) "" else query.joinToString("&")
        return try {
            httpProtocol.getAsync(host + name, value, converter).await()
        } catch (e: Exception) {
            converter.onConvert(null)
        }
    }


    private fun apiRequest(name: String, vararg query: String): Response {
        val value = if (query.isEmpty()) "" else query.joinToString("&")
        return try {
            return httpProtocol.get(host + name, value, apiResponseConverter)
        } catch (e: Exception) {
            Response()
        }
    }

}